package com.lancoo.edu.platform.operation.commons.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * Web 配置类
 *
 * @author pky
 */
@SpringBootConfiguration
public class WebConfig implements WebMvcConfigurer {

    /**
     * 图片保存路径，自动从properties文件中获取数据
     */
    @Value("${file-save-path}")
    private String fileSavePath;
    /**
     * 资源映射路径
     */
    @Value("${file-mapping}")
    private String fileMapping;

    @Value("${project.path}")
    private String projectPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        /*
         * 配置资源映射
         * 意思是：如果访问的资源路径是以“/upload/”开头的，
         * 就给我映射到本机的“D:/upload/”这个文件夹内，去找你要的资源
         * 注意：D:/upload/ 后面的 “/”一定要带上
         */
        registry.addResourceHandler(fileMapping + "**").addResourceLocations("file:" + fileSavePath);
        registry.addResourceHandler("/logo/" + "**").addResourceLocations("file:" + projectPath + "logo/");
        registry.addResourceHandler("/" + "**").addResourceLocations("file:" + projectPath + "static/");


    }

    /**
     * 开放跨域
     *
     * @param registry 跨域注册器
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                //放行全部请求方式
//                .allowedMethods("*")
                .allowedMethods("GET", "HEAD", "POST", "PUT", "DELETE", "OPTIONS")
                //是否发送Cookie
                .allowCredentials(true)
                .maxAge(3600)
                //暴露哪些原始请求头部信息
                .exposedHeaders("Access-Control-Allow-Origin")
                //放行哪些原始请求头部信息
                .allowedHeaders("*");
    }

}
